<?php
declare (strict_types = 1);

namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
class Setting extends \app\admin\controller\Base
{
  
  public function insert()
  {
    $post = input('post.');
    $group = input('group');
    $type = input('type');
    $field = input('field');
    $ck = Db::name('setting')->where('field',$field)
                            ->where('group',$group)
                            ->where('type',$type)
                            ->find();
    if ($ck) {
      return $this->doError('field,group,type必须同时唯一');
    }
    Db::name('setting')->insert($post);
    return $this->doSuccess('ok',$ck);
  }

  public function saveGroup()
  {
    $rows = input('post.');
    foreach ($rows as $k) {
      foreach ($k['rows'] as $key) {
        Db::name('setting')->where('id',$key['id'])->update([
          'value'=>$key['value']
        ]);
      }
    }
    return $this->doSuccess('ok');
  }

  public function getGroup()
  {
    $group = input('group','union');
    $rows = Db::name('setting')
                  ->where('group',$group)
                  ->select()->toArray();

    $type = Db::name('setting')
                  ->field('type')
                  ->group('type')
                  ->where('group',$group)
                  ->select()->toArray();
    foreach ($type as &$k) {
      $rows = Db::name('setting')
                  ->where('type',$k['type'])
                  ->where('group',$group)
                  ->select()->toArray();
      $k['rows'] = $rows;
    }
    return $this->doSuccess('ok',$type);
  }

}
